import React from 'react';
import { Card, Space, Button, Form, Input, Select, DatePicker, Table, Tag, Popconfirm, message } from 'antd';

const { RangePicker } = DatePicker;

// Mock operation log data
const initialData = Array.from({ length: 30 }).map((_, i) => ({
  id: i + 1,
  username: ['alice', 'bob', 'charlie'][i % 3],
  account: ['A001', 'B002', 'C003'][i % 3],
  module: ['设备', '活动', '用户'][i % 3],
  action: ['新增', '编辑', '删除'][i % 3],
  path: ['/api/device', '/api/activity', '/api/user'][i % 3],
  method: ['POST', 'PUT', 'DELETE'][i % 3],
  status: i % 5 === 0 ? '失败' : '成功',
  duration: (i % 7) * 123 + 80,
  ip: `10.0.0.${i + 20}`,
  time: `2025-10-${(i % 27) + 1} 14:${(i % 60).toString().padStart(2, '0')}:22`,
  remark: i % 5 === 0 ? '接口返回异常' : '—',
}));

export default function OperationLog() {
  const [form] = Form.useForm();
  const [data, setData] = React.useState(initialData);
  const [filters, setFilters] = React.useState({});

  const filteredData = React.useMemo(() => {
    return data.filter((row) => {
      const { username, account, module, status, path, action } = filters;
      const f = [
        username ? row.username?.toLowerCase().includes(username.toLowerCase()) : true,
        account ? row.account?.toLowerCase().includes(account.toLowerCase()) : true,
        module ? row.module === module : true,
        status ? row.status === status : true,
        path ? row.path?.toLowerCase().includes(path.toLowerCase()) : true,
        action ? row.action === action : true,
      ];
      return f.every(Boolean);
    });
  }, [data, filters]);

  const columns = [
    { title: 'ID', dataIndex: 'id', width: 70 },
    { title: '用户名', dataIndex: 'username', width: 120 },
    { title: '账号', dataIndex: 'account', width: 120 },
    { title: '模块', dataIndex: 'module', width: 100 },
    { title: '操作', dataIndex: 'action', width: 100 },
    { title: '接口路径', dataIndex: 'path', width: 180 },
    { title: '方法', dataIndex: 'method', width: 90 },
    { title: '耗时(ms)', dataIndex: 'duration', width: 100 },
    { title: 'IP', dataIndex: 'ip', width: 130 },
    {
      title: '结果',
      dataIndex: 'status',
      width: 90,
      render: (v) => (v === '成功' ? <Tag color="green">成功</Tag> : <Tag color="red">失败</Tag>),
    },
    { title: '时间', dataIndex: 'time', width: 180 },
    { title: '备注', dataIndex: 'remark' },
    {
      title: '操作',
      fixed: 'right',
      width: 100,
      render: (_, row) => (
        <Space>
          <Popconfirm title="删除此日志？" onConfirm={() => onDelete(row.id)}>
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  function onSearch() {
    const values = form.getFieldsValue();
    setFilters({
      username: values.username || '',
      account: values.account || '',
      module: values.module || '',
      status: values.status || '',
      path: values.path || '',
      action: values.action || '',
      range: values.range || null,
    });
  }

  function onReset() {
    form.resetFields();
    setFilters({});
  }

  function onDelete(id) {
    setData((prev) => prev.filter((x) => x.id !== id));
    message.success('已删除');
  }

  function onClear() {
    setData([]);
    message.success('已清空');
  }

  function onExport() {
    const blob = new Blob([JSON.stringify(filteredData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'operation-log.json';
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <Space direction="vertical" size={16} style={{ width: '100%' }}>
      <Card
        title="操作日志"
        extra={
          <Space>
            <Button onClick={onExport}>导出</Button>
            <Popconfirm title="确认清空所有日志？" onConfirm={onClear}>
              <Button danger>清空</Button>
            </Popconfirm>
          </Space>
        }
      >
        <Form form={form} layout="inline">
          <Form.Item label="用户名" name="username">
            <Input placeholder="请输入用户名" allowClear style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label="账号" name="account">
            <Input placeholder="请输入账号" allowClear style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label="模块" name="module">
            <Select allowClear placeholder="全部" style={{ width: 150 }} options={[
              { value: '设备', label: '设备' },
              { value: '活动', label: '活动' },
              { value: '用户', label: '用户' },
            ]} />
          </Form.Item>
          <Form.Item label="操作" name="action">
            <Select allowClear placeholder="全部" style={{ width: 150 }} options={[
              { value: '新增', label: '新增' },
              { value: '编辑', label: '编辑' },
              { value: '删除', label: '删除' },
            ]} />
          </Form.Item>
          <Form.Item label="接口路径" name="path">
            <Input placeholder="请输入接口路径关键词" allowClear style={{ width: 220 }} />
          </Form.Item>
          <Form.Item label="结果" name="status">
            <Select allowClear placeholder="全部" style={{ width: 150 }} options={[
              { value: '成功', label: '成功' },
              { value: '失败', label: '失败' },
            ]} />
          </Form.Item>
          <Form.Item label="时间范围" name="range" style={{ marginTop: 12 }}>
            <RangePicker showTime  />
          </Form.Item>
          <Space style={{ marginLeft: 8 ,marginTop: 12 }}>
            <Button type="primary" onClick={onSearch} style={{ height: 36 }}>查询</Button>
            <Button onClick={onReset} style={{ height: 36 }}>重置</Button>
          </Space>
        </Form>
      </Card>

      <Card>
        <Table
          size="small"
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>
    </Space>
  );
}